var kue  = require('kue'),
	jobs = kue.createQueue(),
	gm   = require('gm'),
	fs   = require('fs'),
	path = require('path'),
	thumbnail = [];

var nodeBIS = require('node_bis');

console.log('Processor started.');
  
jobs.process('GenerateThumbnail', 1, function(job, done){
    console.log( 'generating thumbnail for', job.data.fileName );
	var filePath = path.normalize(job.data.path + job.data.fileName);
	var binData = '';
	var thumbDimension = 300;
	var width,height;
	
	// console.log(job.data);

	gm( filePath ).size( function( err, value ) {
		var thumbName = new Date().getTime() + '-thumb.jpg';
		var thumbFile = path.normalize(__dirname + '/tmp/' + thumbName); // Uses local cache from app
		var id = job.data.id;

		if('undefined' != typeof value) {
			var width = value.width;
			var height = value.height;
		    if ( value.width > value.height ) {
                width = thumbDimension;
				height = value.height * (thumbDimension / value.width);
			} else {
                height = thumbDimension;
				width = value.width * (thumbDimension / value.height);
			}
		} else {
			width = thumbDimension;
            height = thumbDimension;
		}
		gm( filePath ).thumb(width, height, thumbFile, 90, function(err, stdout, stderr, command) {
			if ( fs.existsSync(thumbFile) ) {
				fs.createReadStream( thumbFile, {'encoding': 'binary'} )
					.addListener( 'data', function( chunk ) {
						binData += chunk;
                    }).addListener( 'close',function() {
						console.log( 'Thumbnail Created', id );
						var uploadJob = jobs.create( 'UpdateImage', {id: id, binData: binData} ).save();
						fs.unlink( thumbFile );
                    });
			} else {
                console.log( thumbFile, ' not created.' );
            }
		});
		done();
	});
});

jobs.process( 'AddBisImage', 10, function( job, done ) {
	var bisN = new nodeBIS( job.data.obj.key, job.data.obj.url, job.data.obj.path );
	bisN.addImage( path.normalize(job.data.folderPath), job.data.path, job.data.path, job.data.remotePath, function( imgData, err ) {
		if ( imgData ) {
            try {
                imgData = JSON.parse( imgData );
            } catch ( err ) {
                // pass
            }
            if ( imgData.success ) {
                if ( imgData.records.length > 0 ) {
                    if ( imgData.records[0].success ) {
                        var bisImageId = imgData.records[0].imageId;
                        var uploadJob = jobs.create( 'BisImageAdded', {imageId: job.data.imageId, bisId: job.data.bisId, bisImageId: bisImageId} ).save();
                        console.log( 'Uploaded image', bisImageId );
                    } else {
                        // add error message to database
                        jobs.create( 'BISImageUploadError', { imageId: job.data.imageId, message: imgData.records[0].error.msg, code: imgData.records[0].error.code } ).save();
                        console.log( 'Unable to upload image ' + job.data.imageId + '. See error for details.' );
                    }
                } else {
                    console.log( 'No results uploading image.' );
                }
            } else {
                console.log( imgData );
                //console.log( 'There was an error uploading the image (code '+ imgData.error.code +'):', imgData.error.msg );
            }
		} else {
            console.log( 'Error uploading image', err );
        }
	});
	done();
});

jobs.process( 'DeleteBisImage', 10, function( job, done ) {
	var bisN = new nodeBIS( job.data.config.server.key, job.data.config.server.url, job.data.config.server.path );
	bisN.deleteImage({ imageId: job.data.imageId, bisImageId: job.data.bisImageId, bisId: job.data.bisId }, function( imgData, err ) {
		if ( imgData ) {
			jobs.create( 'BisImageDeleted', {
                imageId: job.data.imageId,
                bisId: job.data.bisId,
                bisImageId: job.data.bisImageId
            }).save();
		}
	});
	done();
});

jobs.process( 'AddBisImageAttribute', 2, function( job, done ) {
	var bisN = new nodeBIS( job.data.config.server.key, job.data.config.server.url, job.data.config.server.path );
	bisN.addImageAttribute({
        imageId: job.data.bisImageId,
        categoryId: job.data.categoryId,
        attributeId: job.data.attributeId
    }, function( imgData, err ) {
		if ( imgData != false ) {
			var uploadJob = jobs.create( 'BisImageAttributeAdded', {
                imageId: job.data.imageId,
                name: job.data.name,
                bisId: job.data.bisId,
                bisImageId: job.data.bisImageId,
                categoryId: job.data.categoryId,
                attributeId: job.data.attributeId
            }).save();
		}
	});
	done();
});

jobs.process( 'DeleteBisImageAttribute', 10, function( job, done ) {
	var bisN = new nodeBIS( job.data.obj.key, job.data.obj.url, job.data.obj.path );
	bisN.deleteImageAttribute({
        imageId: job.data.bisImageId,
        categoryId: job.data.categoryId,
        attributeId: job.data.attributeId
    }, function( imgData, err ) {
		if ( imgData ) {
			var uploadJob = jobs.create( 'BisImageAttributeDeleted', {
                imageId: job.data.imageId,
                bisId: job.data.bisId,
                bisImageId: job.data.bisImageId,
                categoryId: job.data.categoryId,
                attributeId: job.data.attributeId
            }).save();
		}
	});
	done();
});

jobs.process( 'CreateBisCategory', 2, function( job, done ) {
    // config comes from bisc.settings
    // config must include the current server settings
    var bisNode = new nodeBIS( job.data.config.server.key, job.data.config.server.url, job.data.config.server.path );
    bisNode.createCategory({
        title: job.data.title,
        description: job.data.description,
        elementSet: job.data.elementSet,
        term: job.data.term
    }, function( imageData, response ) {
        if ( imageData ) {
            job.data.categoryId = response;
            console.log( 'New category created on BIS server', job.data.categoryId );
            jobs.create( 'BisCategoryCreated', job.data ).save();
        } else {
            console.log( 'There was a problem creating the bis category:', response );
        }
        done();
    });
});

jobs.process( 'CreateBisAttribute', 2, function( job, done ) {
    // config comes from bisc.settings
    // config must include the current server settings
    var bisNode = new nodeBIS( job.data.config.server.key, job.data.config.server.url, job.data.config.server.path );
    bisNode.createAttribute({
        name: job.data.name,
        categoryId: job.data.categoryId
    }, function( imageData, response ) {
        if ( imageData ) {
            job.data.attributeId = response;
            console.log( 'New attribute created on BIS server', job.data.attributeId );
            jobs.create( 'BisAttributeCreated', job.data ).save();
        } else {
            console.log( 'There was a problem creating the bis attribute:', response );
        }
        done();
    });
});
